package com.xiashitech.agent.instrumentation.async.boot;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 异步句柄持有者
 * @author zhoayk
 */
public class AsyncFutureHolder {

    private static ThreadLocal<List<Object>> threadLocal = new ThreadLocal<>();

    public static void wait(CompletableFuture<?> completableFuture, AsyncCallback callback) {
        List<Object> list = threadLocal.get();
        if(list == null)
            threadLocal.set(list = new ArrayList<>());

        list.add(completableFuture);
        list.add(callback);
        //DebugUtils.print4Debug("AsyncFutureHolder.wait list", list != null ? "size: " + list.size() : "list is null");
    }

    public static AsyncCallback<?, ?> fetch(CompletableFuture<?> completableFuture) {
        List<Object> list = threadLocal.get();
        //DebugUtils.print4Debug("AsyncFutureHolder.fetch list", list != null ? "size: " + list.size() : "list is null");
        if(list != null) {
            for (int i = 0; i < list.size(); i += 2) {
                Object o = list.get(i);
                if(o == completableFuture) {
                    Object callback = list.get(i + 1);

                    list.remove(i);
                    list.remove(i);
                    if(list.size() == 0)
                        threadLocal.remove();

                    return (AsyncCallback<?, ?>) callback;
                }
            }
        }
        return null;
    }

    public static void release() {
        threadLocal.remove();
    }

}
